<?php
Yii::import('zii.behaviors.CTimestampBehavior');

class AuditStampBehavior extends CTimestampBehavior {
	public $createAttribute = 'createTime';
	public $updateAttribute = 'updateTime';

	public $createUserAttribute = 'createUserId';
	public $updateUserAttribute = 'updateUserId';

	public function beforeSave($event) {
		parent::beforeSave($event);
		if (!isset(Yii::app()->user)) {
			return;
		}
		$user = Yii::app()->user;
		if (!$user->isGuest) {
			if ($this->getOwner()->getIsNewRecord() && ($this->createUserAttribute !== null)) {
				$this->getOwner()->{$this->createUserAttribute} = $user->id;
			}
			if ((!$this->getOwner()->getIsNewRecord() || $this->setUpdateOnCreate)
				&& ($this->updateUserAttribute !== null)) {
				$this->getOwner()->{$this->updateUserAttribute} = $user->id;
			}
		}
	}
}
